package service

import (
	"log"
	"os"
	"runtime"
)

// ServiceInfo 服务信息结构
type ServiceInfo struct {
	Name         string            `json:"name"`
	DisplayName  string            `json:"display_name"`
	Description  string            `json:"description"`
	Status       string            `json:"status"`
	State        string            `json:"state"`
	PID          int               `json:"pid"`
	Memory       string            `json:"memory,omitempty"`
	CPU          string            `json:"cpu,omitempty"`
	ExitCode     int               `json:"exit_code,omitempty"`
	StartType    string            `json:"start_type,omitempty"` // Windows 专用
	BinaryPath   string            `json:"binary_path,omitempty"`
	Dependencies []string          `json:"dependencies,omitempty"`
	Environment  map[string]string `json:"environment,omitempty"`
}

// Service 服务管理器接口
type Service interface {
	Status(serviceName string) (*ServiceInfo, error)
	Start(serviceName string) error
	Stop(serviceName string) error
	Restart(serviceName string) error
	List() ([]ServiceInfo, error)
	Logs(serviceName string, lines int) (string, error)
	IsRunning(serviceName string) (bool, error)
	Enable(serviceName string) error
	Disable(serviceName string) error
}

// ServiceManager 跨平台服务管理器
type ServiceManager struct {
	manager Service
	logger  *log.Logger
}

// NewServiceManager 创建跨平台服务管理器
func NewServiceManager() *ServiceManager {
	var manager Service

	switch runtime.GOOS {
	case "windows":
		manager = NewWindowsServiceManager()
	case "linux":
		manager = NewLinuxServiceManager()
	case "darwin":
		manager = NewDarwinServiceManager()
	default:
		// 默认为 Linux 管理器
		manager = NewLinuxServiceManager()
	}

	return &ServiceManager{
		manager: manager,
		logger:  log.New(os.Stdout, "[ServiceManager] ", log.LstdFlags),
	}
}

// 实现 ServiceManager 接口的所有方法
func (cpm *ServiceManager) Status(serviceName string) (*ServiceInfo, error) {
	return cpm.manager.Status(serviceName)
}

func (cpm *ServiceManager) Start(serviceName string) error {
	return cpm.manager.Start(serviceName)
}

func (cpm *ServiceManager) Stop(serviceName string) error {
	return cpm.manager.Stop(serviceName)
}

func (cpm *ServiceManager) Restart(serviceName string) error {
	return cpm.manager.Restart(serviceName)
}

func (cpm *ServiceManager) List() ([]ServiceInfo, error) {
	return cpm.manager.List()
}

func (cpm *ServiceManager) Logs(serviceName string, lines int) (string, error) {
	return cpm.manager.Logs(serviceName, lines)
}

func (cpm *ServiceManager) IsRunning(serviceName string) (bool, error) {
	return cpm.manager.IsRunning(serviceName)
}

func (cpm *ServiceManager) Enable(serviceName string) error {
	return cpm.manager.Enable(serviceName)
}

func (cpm *ServiceManager) Disable(serviceName string) error {
	return cpm.manager.Disable(serviceName)
}
